<template>
  <div class="article-list">
    <van-pull-refresh
      v-model="refreshing"
      @refresh="onRefresh"
      :success-text="refreshText"
      :success-duration="1500"
    >
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        :error.sync="err"
        error-text="请求失败，点击重新加载"
        @load="onLoad"
      >
        <!-- <van-cell v-for="(item, ind) in list" :key="ind" :title="item.title" /> -->
        <ArticleItem
          v-for="(item, ind) in list"
          :key="ind"
          :article="item"
        ></ArticleItem>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getArticle } from '../api/article';
import ArticleItem from './article-item';
export default {
  name: 'ArticleList',
  components: { ArticleItem },
  props: {
    channel: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      list: [],
      loading: false,
      finished: false,
      timestamp: null,
      err: false,
      refreshing: false,
      refreshText: '刷新成功！'
    };
  },
  computed: {},
  watch: {},
  created () {
    this.getArticleFn();
  },
  mounted () {},
  methods: {
    async onLoad () {
      // 异步更新数据
      // setTimeout 仅做示例，真实场景中一般为 ajax 请求
      try {
        const {
          data: { data }
        } = await getArticle({
          channel_id: this.channel.id,
          timestamp: this.timestamp || Date.now()
        });

        this.list.push(...data.results);
        this.loading = false;
        if (data.results.length) {
          this.timestamp = data.pre_timestamp;
        } else {
          this.finished = false;
        }
        if (this.list.length >= data.results.length) {
          this.finished = true;
        }
      } catch (error) {
        this.err = true;
        this.loading = false;
      }
    },
    async getArticleFn () {},
    async onRefresh () {
      // 清空列表数据
      try {
        const {
          data: { data }
        } = await getArticle({
          channel_id: this.channel.id,
          timestamp: Date.now()
        });
        // 模拟失败
        // if (Math.random() > 0.5) {
        //   JSON.parse("dsnajndjsa");
        // }
        this.list.unshift(...data.results);
        this.refreshing = false;
        this.refreshText = `刷新成功，更新了${data.results.length}条数据`;
      } catch (error) {
        this.refreshing = false;

        this.refreshText = '刷新失败';
      }
    }
  }
};
</script>

<style scoped lang="less">
.article-list {
  height: 79vh;
  overflow-y: auto;
}
</style>
